<template>
    <div class="marquee-container">
        <div class="marquee-content" :style="contentStyle">
            <span class="text-item">{{ text }}</span>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'

const text = ref('剧本杀预约平台全新上线！精选悬疑、情感、恐怖等海量剧本，专业实景场馆任你选。新用户专享优惠，组队拼车更划算，智能匹配快速开局。一键预约，随时开玩，开启你的沉浸式推理之旅！')
const position = ref(0)
let animationFrameId = null
const speed = 0.6 // 滚动速度（像素/帧）
const containerWidth = 1200 // 容器宽度
let textWidth = ref(0)
let isAnimating = ref(true)

const contentStyle = computed(() => ({
    transform: `translateX(${position.value}px)`,
    display: isAnimating.value ? 'block' : 'none'
}))

const animate = () => {
    position.value -= speed

    // 当文字完全滚出容器时停止动画
    if (position.value <= -textWidth.value) {
        position.value = containerWidth
    }

    animationFrameId = requestAnimationFrame(animate)
}

onMounted(() => {
    // 获取文字实际宽度
    const tempSpan = document.createElement('span')
    tempSpan.style.visibility = 'hidden'
    tempSpan.style.whiteSpace = 'nowrap'
    tempSpan.textContent = text.value
    document.body.appendChild(tempSpan)
    textWidth.value = tempSpan.offsetWidth
    document.body.removeChild(tempSpan)

    // 初始位置：从容器右侧开始
    position.value = containerWidth

    // 开始动画
    animate()
})

</script>

<style scoped>
.marquee-container {
    width: 1200px;
    height: 40px;
    background-color: #f5f5f5;
    border: 1px solid #ddd;
    overflow: hidden;
    white-space: nowrap;
    position: relative;
    margin: 0 auto;
}

.marquee-content {
    position: absolute;
    line-height: 40px;
    white-space: nowrap;
    color: #6a11cb;
    will-change: transform;
    left: 0;
}

.text-item {
    display: inline-block;
}
</style>